package cn.java.exercises;

public class EquationRoot
{
    private int a;
    private int b;
    private int c;

    public EquationRoot(int a, int b, int c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public double[] getEquationRoot()
    {
        double results[]=new double[2];
        double delta;
        delta=Math.pow(b,2)-4*a*c;

        if(delta >=0)
        {
            results[0]=((-1)*b+Math.sqrt(delta))/(2*a);
            results[1]=((-1)*b-Math.sqrt(delta))/(2*a);
            return results;
        }
        else
        {
            return null;
        }
    }

    //f(x)=ax^2+bx+c
    private double f(double x)
    {
        return a*x*x+b*x+c;
    }

    //f(x)导数=2ax+b
    private double fx(double x)
    {
        return 2.0*x*a+b;
    }

    private double newtonInteration(double x0,double accuracy)
    {
        double result,x1;
        x1=x0-f(x0)/fx(x0);
        while (Math.abs(x1-x0)>accuracy)
        {
            x0=x1;
            x1=x0-f(x0)/fx(x0);
        }
        return x1;
    }

    public double[] getRootByNewtonInteration(double accuracy)
    {
        double results[]=new double[2];
        double x0=(-b)/(2*a)+10;
        results[0]=newtonInteration(x0,accuracy);
        x0=(-b)/(2*a)-10;
        results[1]=newtonInteration(x0,accuracy);

        return results;
    }
}

class EquationRootDemo
{
    public static void main(String[] args)
    {
        int a=1,b=2,c=1;
        EquationRoot eqRoot=new EquationRoot(a,b,c);
        double roots[];
        roots=eqRoot.getEquationRoot();
        String strMsg=String.format("%dx^2+%dx+%d=0的根是：%2.2f,%2.2f",
                                    a,b,c,roots[0],roots[1]);
        System.out.println(strMsg);
        roots=eqRoot.getRootByNewtonInteration(0.0001);
        strMsg=String.format("牛顿迭代法求解方程式%dx^2+%dx+%d=0的根是：%2.2f,%2.2f",
                             a,b,c,roots[0],roots[1]);
        System.out.println(strMsg);
    }
}
